use std::{iter::FromIterator, net::SocketAddr};

fn main() {
    Solution::reverse_words(format!("Hello world"));
}
struct Solution;
impl Solution {
    pub fn reverse_words(s: String) -> String {
        /// 反转范围为 [start..=end]
        fn reverse_string(cs: &mut Vec<char>, mut start: usize, mut end: usize) {
            while start < end {
                let temp = cs[start];
                cs[start] = cs[end];
                cs[end] = temp;
                start += 1;
                end -= 1;
            }
        }
        let mut ans = s.chars().collect::<Vec<char>>();
        let n = ans.len();
        let mut last = 0;
        for i in 1..n {
            if ans[i] == ' ' {
                reverse_string(&mut ans,last,i - 1);
                last = i + 1;
            }
        }
        reverse_string(&mut ans,last,n - 1);
        return String::from_iter(ans);
    }
}
